package com.biz.primus.ms.payment.service;

import com.biz.primus.common.utils.JsonUtil;
import com.biz.primus.ms.base.service.AbstractBaseService;
import com.biz.primus.ms.payment.channel.wechat.res.WechatPayNotifyRespVo;
import com.biz.primus.ms.payment.dao.po.WechatPaymentLogPo;
import com.biz.primus.ms.payment.dao.repository.WechatPaymentLogRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;

@Slf4j
@Service
public class WechatPaymentLogService extends AbstractBaseService {

    private final WechatPaymentLogRepository paymentLogRepository;

    @Autowired
    public WechatPaymentLogService(WechatPaymentLogRepository paymentLogRepository) {
        this.paymentLogRepository = paymentLogRepository;
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void logWechatPaymentNotify(WechatPayNotifyRespVo notifyRes, Long paymentOrderId) {
        try {
            String notifyJson = JsonUtil.obj2Json(notifyRes.getProperties());
            log.info("log wechat payment notify:'{}'", notifyJson);

            WechatPaymentLogPo paymentLog = new WechatPaymentLogPo();
            paymentLog.setId(idService.getNextId());
            paymentLog.setOrderPaymentId(paymentOrderId);
            paymentLog.setTransactionId(notifyRes.getTransactionId());
            paymentLog.setLog(notifyJson);
            paymentLog.setTs(new Timestamp(System.currentTimeMillis()));
            paymentLog.setResultCode(notifyRes.getResultCode());
            paymentLog.setErrCode(notifyRes.getErrorCode());
            paymentLog.setErrCodeDes(notifyRes.getErrorDescption());
            paymentLog.setOpenid(notifyRes.getOpenId());
            paymentLog.setTradeType(notifyRes.getTradeType());
            paymentLog.setBankType(notifyRes.getBankType());
            paymentLog.setTotalFee(notifyRes.getTotalFee());
            paymentLog.setFeeType(notifyRes.getFeeType());
            paymentLog.setCashFee(notifyRes.getCashFee());
            paymentLog.setCashFeeType(notifyRes.getCashFeeType());
            paymentLog.setCouponFee(notifyRes.getCouponFee());
            paymentLog.setCouponCount(notifyRes.getCouponCount());
            paymentLog.setCouponId(notifyRes.getCouponId());
            paymentLog.setAttach(notifyRes.getAttach());
            paymentLog.setTimeEnd(new Timestamp(notifyRes.getTimeEnd().getTime()));
            paymentLogRepository.save(paymentLog);
        } catch (Exception e) {
            log.info("record wechat payment log failed.", e);
        }
    }
}
